#!/bin/bash
usage="createvm <vmname> <osname> <ram> <vrdpport> <vrdpaddress> <originalVDI> <targetVdiFolder> <hddsize> <cores> <zeusclientport>"

if [ $# -eq 0 ]
then
	echo -e "\n Usage : $usage\n"
	exit 100
fi

echo -e "\n\tCreating VM\n"
cmd="VBoxManage createvm --name $1 --ostype $2 --register"
echo -e "\n\t$cmd\n"
$cmd
if [ $? -ne 0 ]
then
	echo -e "\n\tFatal Error in $cmd\n"
	exit 1
fi

portForward=$(($4+1))
cmd="VBoxManage modifyvm $1 --memory $3 --nic1 nat --natpf1 zeusport,tcp,,$portForward,,${10} --vrdp on --vrdpport $4 --vrdpaddress $5 --vrdpvideochannelquality 80  --boot1 dvd --boot2 disk --cpus $9"
echo -e "\n\t$cmd\n"
$cmd
if [ $? -ne 0 ]
then
	echo -e "\n\tFatal Error in $cmd\n"

	cmd="VBoxManage unregistervm $1 --delete"
	echo -e "\n\t$cmd\n"
	$cmd
	exit 2
fi

newPrimaryHdd="$7/$1OS.vdi"
newSecondaryHdd="$7/$1HDD.vdi"
cmd="VBoxManage clonehd $6 $newPrimaryHdd --format VDI"
echo -e "\n\t$cmd\n"
$cmd

if [ $? -ne 0 ]
then
	echo -e "\n\tFatal Error in $cmd\n"
	cmd="VBoxManage unregistervm $1 --delete"
	echo -e "\n\t$cmd\n"
	$cmd
	cmd="rm $newPrimaryHdd"
	echo -e "\n\t$cmd\n"
	$cmd
	exit 3
fi

cmd="VBoxManage storagectl $1 --name \"IDE Controller\" --add ide"
echo -e "\n\t$cmd\n"
VBoxManage storagectl $1 --name "IDE Controller" --add ide

if [ $? -ne 0 ]
then
	echo -e "\n\tFatal Error in $cmd\n"
	exit 4
fi

cmd="VBoxManage storageattach $1 --storagectl 'IDE Controller' --port 0 --device 0 --type hdd --medium $newPrimaryHdd"
echo -e "\n\t$cmd\n"
VBoxManage storageattach $1 --storagectl 'IDE Controller' --port 0 --device 0 --type hdd --medium $newPrimaryHdd

if [ $? -ne 0 ]
then
	echo -e "\n\tFatal Error in $cmd\n"
		cmd="rm $newPrimaryHdd"
	echo -e "\n\t$cmd\n"
	$cmd
	cmd="VBoxManage unregistervm $1 --delete"
	echo -e "\n\t$cmd\n"
	$cmd
	exit 5
fi
cmd="VBoxManage createhd --filename $newSecondaryHdd --size $8 --register"
echo -e "\n\t$cmd\n"
$cmd

if [ $? -ne 0 ]
then
	echo -e "\n\tFatal Error in $cmd\n"
	cmd="rm $newPrimaryHdd"
	echo -e "\n\t$cmd\n"
	$cmd
	cmd="rm $newSecondaryHdd"
	echo -e "\n\t$cmd\n"
	$cmd
	cmd="VBoxManage unregistervm $1 --delete"
	echo -e "\n\t$cmd\n"
	$cmd
	exit 6
fi



cmd="VBoxManage storageattach $1 --storagectl 'IDE Controller' --port 1 --device 0 --type hdd --medium $newSecondaryHdd"
echo -e "\n\t$cmd\n"
VBoxManage storageattach $1 --storagectl 'IDE Controller' --port 1 --device 0 --type hdd --medium $newSecondaryHdd

if [ $? -ne 0 ]
then
	echo -e "\n\tFatal Error in $cmd\n"
	cmd="rm $newPrimaryHdd"
	echo -e "\n\t$cmd\n"
	$cmd
	cmd="rm $newSecondaryHdd"
	echo -e "\n\t$cmd\n"
	$cmd
	cmd="VBoxManage unregistervm $1 --delete"
	echo -e "\n\t$cmd\n"
	$cmd
	exit 7
fi

exit 0
